<template>
  <com-el-dialog-ex
    title="创建权限"
    v-model:visible="visible"
    @open="resetForm"
    @confirm="submitForm"
    @cancel="closed"
  >
    <el-form ref="ruleFormRef" label-width="auto" size="default" :model="ruleForm" :rules="rules">
      <el-form-item prop="authorityName" label="权限名称：">
        <el-input clearable v-model="ruleForm.authorityName" placeholder="请输入权限名称" />
      </el-form-item>
      <el-form-item prop="authorityPath" label="权限路径：">
        <el-input clearable v-model="ruleForm.authorityPath" placeholder="请输入权限路径" />
      </el-form-item>
      <el-form-item prop="description" label="描述：" >
        <el-input clearable v-model="ruleForm.description" type="textarea" :rows="3" placeholder="请输入描述" class="input-content"/>
      </el-form-item>
    </el-form>
  </com-el-dialog-ex>
</template>

<script setup lang="ts">
import { getCurrentInstance } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { defaultForm, type DefaultForm, formRule } from '@/common/model/authority/defaultForm'
import ComElDialogEx from '@/components/com-el-dialog-ex/com-el-dialog-ex.vue'

defineOptions({
  name: 'AddAuthorityView',
})

//region # 属性

// 应用实例
const { proxy }: any = getCurrentInstance()

// 显示状态
const visible = defineModel('visible', {
  type: Boolean,
  required: true,
  default: false,
})

// 表单
const ruleFormRef = ref<FormInstance>()

// 验证表单
let ruleForm = reactive<DefaultForm>(defaultForm)

// 验证规则
const rules = reactive<FormRules<DefaultForm>>(formRule)

// 组件事件列表
const emits = defineEmits(['closed'])

//endregion

//region # Hooks

//endregion

//region # 方法

// Action

/**
 * 提交
 * */
const submitForm = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      //创建权限
      await proxy.$api.authority.createAuthority('711E7A93-191C-467F-BAAA-4C8DEB69A269',ruleForm.authorityName, ruleForm.authorityPath, ruleForm.description)
      proxy.$service.toast.success('创建权限成功！')
      tryClose(true)
    }
  })
}

/**
 * 重置表单
 * */
const resetForm = () => {
  if (!ruleFormRef.value) return
  ruleForm = Object.assign(ruleForm, defaultForm)
  ruleFormRef.value.resetFields()
}

/**
 * 重置表单
 * */
const closed = () => {
  tryClose(false)
}

/**
 * 尝试关闭
 * @param result - 结果
 * */
const tryClose = (result: boolean) => {
  visible.value = false
  emits('closed', result)
}

//endregion

//region # 事件

/**
 * 加载完毕
 * */
onMounted(async () => {})
//endregion
</script>

<style scoped>
@import 'AddAuthorityView.less';
</style>
